<template>
	<view style="overflow: hidden;height: 100%;">
		<!-- <CustomNavbar :title="pageTitle" :rightButtons="rightBtns" @share="onShare" /> -->
		<view style="height: 100px;line-height: 135px;text-align: center;font-size: 14px;font-weight: bold;">
			电脑申领
		</view>
		<view class="container">
			<view class="form-container">
				<view class="form-group">
					<view class="label">申领电脑名称</view>
					<input type="text" class="input" placeholder="请输入电脑名称" v-model="formData.applyMaterialName" />
				</view>
				<view class="form-group">
					<view class="label">申领电脑数量</view>
					<input type="text" class="input" placeholder="请输入数量" v-model="formData.applyMaterialCount" />
				</view>
				<view class="form-group">
					<view class="label">申领时间</view>
					<picker mode="date" :value="formData.applyMaterialTime" start="1900-01-01" end="2025-12-31"
						@change="handleApplyChange">
						<view class="picker">
							{{ formData.applyMaterialTime || '请选择申领时间' }}
						</view>
					</picker>
				</view>
				<view class="form-group">
					<view class="label">电脑序列号</view>
					<input type="text" class="input" placeholder="请输入序列号" v-model="formData.applyMaterialCode" />
				</view>

				<view class="form-group">
					<view class="label">申领状态</view>
					<picker @change="changePickerPost" :value="materialStatusIndex" :range="statusOptions"
						:range-key="'name'">
						<view class="uni-input" style="font-size: 13px;">{{ statusOptions[materialStatusIndex].name||'请选择申领状态' }}</view>
					</picker>
				</view>
				<view>
					<view class="label">上传图片</view>
					<view class="example-body">
						<uni-file-picker @select="onSelect" @success="uploadSuccess" limit="9"
							title="最多选择9张图片"></uni-file-picker>
					</view>
				</view>
			</view>
			<view class="button-group">
				<button class="btn reset-btn" @click="resetForm">重置</button>
				<button class="btn submit-btn" @click="submitForm">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import CustomNavbar from '@/components/customNavbar.vue'
	import {
		applyMaterialApi,
		ossUploadRecord
	} from '../api/index.js'
	export default {
		components: {
			CustomNavbar
		},
		data() {
			return {
				rightBtns: [{
					icon: 'icon-share',
					callback: 'share'
				}],
				materialPic: [],
				statusOptions: [{
						value: 0,
						name: '已领取'
					},
					{
						value: 1,
						name: '正常退还'
					},
					{
						value: 2,
						name: '损坏退还'
					},
					{
						value: 3,
						name: '丢失'
					},
				],
				materialStatusIndex: 0,
				formData: {
					applyUserType: 1,
					applyMaterialName: '',
					applyMaterialCount: '',
					applyMaterialTime: '',
					uniFileCode: '',
					applyMaterialCode: '',
					materialStatus: 1,

				},
				errors: {},
				selectedDate: ''
			}
		},
		onLaunch: function() {
			console.log(pages.pages)
			const token = uni.getStorageSync('token');
			const targetPath = '/pages/login/login';
			if (token) {
				plus.navigator.closeSplashscreen();
			} else {
				uni.reLaunch({
					url: targetPath
				});
			}
			// uni.reLaunch({ url: targetPath });
		},

		methods: {
			// 上传成功回调
			onSelect(e) {
				this.uploadFile(e.tempFiles[0])

			},
			uploadSuccess(file) {
				console.log('file :>> ', file);
			},
			async uploadFile(file) {
				console.log(file);
				const timestampInSeconds = new Date().getTime();
				const ossObject = JSON.parse(uni.getStorageSync('ossInfo'))
				const uploadResult = uni.uploadFile({
					url: ossObject.host,
					filePath: file.url,
					name: 'file',
					header: {
						'Content-Type': 'multipart/form-data',
						'x-oss-security-token': ossObject.security_token // STS Token
					},
					formData: {
						'success_action_status': '200',
						'policy': ossObject.policy, // 如果使用Policy签名模式，此处需填入后端生成的Policy
						'x-oss-signature': ossObject.signature,
						'x-oss-signature-version': 'OSS4-HMAC-SHA256',
						'x-oss-credential': ossObject.x_oss_credential,
						'x-oss-date': ossObject.x_oss_date,
						'key': ossObject.dir + timestampInSeconds + file.name,
						'x-oss-security-token': ossObject.security_token,
					},
					success: (res) => {
						let imgUrl =
							"https://www.nlpy.cn/oss" +
							"/" +
							ossObject.dir +
							timestampInSeconds +
							file.name;
						this.materialPic.push({
							name: file.name,
							url: imgUrl,
						});
					},
					fail: (error) => {
						console.log('666666666', error)
					}
				})
			},
			buildQueryString(params) {
				const queryArray = [];
				for (const [key, value] of Object.entries(params)) {
					// 处理数组类型的属性
					if (Array.isArray(value)) {
						value.forEach((item, index) => {
							queryArray.push(
								`${encodeURIComponent(key)}=${encodeURIComponent(item)}`
							);
						});
					}
					// 处理普通类型的属性
					else {
						queryArray.push(
							`${encodeURIComponent(key)}=${encodeURIComponent(value)}`
						);
					}
				}

				return queryArray.join('&');
			},
			async uploadMutiple(uuid) {
				const ossFileNames = this.materialPic.map((e) => {
					return e.url
				});
				const params = this.buildQueryString({
					uniFileCode: uuid,
					dictType: 'material_photo',
					dictTypeName: '电脑照片',
					ossFileNames: ossFileNames
				})
				// params.append("uniFileCode", uuid);
				// params.append("dictType", "material_photo");
				// params.append("dictTypeName", "电脑照片");

				// this.materialPic.forEach((e) => {
				// 	params.append("ossFileNames", e.url);
				// });
				await ossUploadRecord(params).then((res) => {
					console.log("res", res);
				});
			},
			changePickerPost(e) {
				this.materialStatusIndex = e.detail.value
			},
			// 设置到校日期
			handleApplyChange(e) {
				console.log(e)
				this.formData.applyMaterialTime = e.detail.value
			},
			formatDate(date) {
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
			},
			generateUUID() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					const r = Math.random() * 16 | 0;
					const v = c === 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			submitForm() {
				// 验证表单
				// if (!this.validateForm()) {
				// 表单验证通过，提交数据
				const uniFileCode = this.generateUUID()
				this.formData.token = JSON.parse(uni.getStorageSync('token'))
				this.formData.materialStatus = this.statusOptions[this.materialStatusIndex].value
				this.formData.uniFileCode = uniFileCode
				if (this.materialPic.length > 0) {
					this.uploadMutiple(uniFileCode);
				}
				// 这里可以添加API请求代码，将数据提交到服务器
				applyMaterialApi(this.formData).then(res => {
					console.log('111111', res.data)
					if (res.data.code == 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						uni.reLaunch({
							url:'/pages/index/success'
						})
					} else {
						uni.showToast({
							title: '提交失败',
							icon: 'error'
						})
						uni.reLaunch({
							url:'/pages/index/success'
						})
					}
				})
				// } else {
				// 	console.log('this.formData', this.formData)
				// 	// 表单验证失败，显示错误信息
				// 	uni.showToast({
				// 		title: '请检查并修正表单错误',
				// 		icon: 'none'
				// 	})
				// }
			}
		},

	}
</script>

<style>
	.container {
		padding: 10px;
		background-color: #f5f5f5;
		height: 80vh;
		overflow-y: auto;
	}

	.form-container {
		background-color: #fff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		margin-bottom: 15px;
	}

	.form-title {
		font-size: 20px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30px;
		color: #333;
	}

	.form-group {
		min-height: 36px;
		margin-bottom: 20px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 5px;
		border-bottom: 1px solid #eaeaea;
	}

	.label {
		font-size: 14px;
		color: #333;
		font-weight: bold;
		width: 30%;
	}

	.input {
		flex: 1;
		height: 40px;
		border: unset;
		padding: 0 5px;
		border-radius: 5px;
		padding: 0 10px;
		font-size: 14px;
		color: #333;
		text-align: right;
	}

	.w-90 {
		width: 90% !important;
	}

	.radio-group {
		display: flex;
		flex-wrap: wrap;
	}

	.radio-item {
		display: flex;
		align-items: center;
		margin-right: 20px;
	}

	.select-time-btn {
		margin-top: 10px;
		padding: 8px 15px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		cursor: pointer;
	}

	.picker {
		height: 40px;
		border: unset;
		border-radius: 5px;
		padding: 0 5px;
		font-size: 14px;
		color: #666;
		display: flex;
		align-items: center;
	}

	.textarea {
		width: 100%;
		min-height: 100px;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
		color: #333;
		resize: none;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 30px;
		margin-bottom: 60px;
	}

	.btn {
		width: 48%;
		height: 45px;
		border-radius: 5px;
		font-size: 16px;
		font-weight: 500;
		cursor: pointer;
	}

	.reset-btn {
		background-color: #f5f5f5;
		color: #666;
		border: 1px solid #ddd;
	}

	.submit-btn {
		background-color: #007aff;
		color: #fff;
		border: none;
	}

	.error-message {
		color: #f56c6c;
		font-size: 12px;
		margin-top: 5px;
	}

	/* 错误状态的输入框样式 */
	.input.error,
	.picker.error,
	.textarea.error {
		border-color: #f56c6c;
	}


	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		padding: 30rpx 0;
		color: #333;
	}

	.card-container {
		padding: 20rpx;
	}

	.card-item {
		margin-bottom: 40rpx;
	}

	.card-label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	.upload-area {
		width: 100%;
		height: 400rpx;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #f9f9f9;
		position: relative;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.upload-placeholder {
		text-align: center;
	}

	.upload-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.upload-hint {
		font-size: 24rpx;
		color: #bbb;
	}

	.delete-btn {
		display: block;
		text-align: center;
		color: #ff4500;
		font-size: 26rpx;
		margin-top: 15rpx;
	}

	.tips {
		padding: 20rpx;
		background-color: #f5f5f5;
		border-radius: 12rpx;
		margin-bottom: 40rpx;
	}

	.tips-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.tips text {
		display: block;
		font-size: 24rpx;
		color: #666;
		line-height: 1.8;
	}

	/* .submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #007aff;
  color: white;
  border-radius: 44rpx;
  font-size: 32rpx;
}

.submit-btn[disabled] {
  background-color: #cccccc;
} */

	.content {
		padding: 30rpx;
	}

	.preview-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-top: 40rpx;
		margin-bottom: 20rpx;
	}

	.preview-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.preview-item {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.preview-item image {
		width: 100%;
		height: 100%;
	}

	.default-box {
		padding: 4px 30px;
		border: 1px solid #EFEBE9;
		border-radius: 4px;
		font-size: 12px;
		color: #333;
		display: flex;
		align-items: center;

	}

	.active-default-box {
		background-color: #007aff;
		color: white;
		border: unset !important;
	}
</style>